package main

import (
	"errors"
	"flag"
	"fmt"
	"httpami/core"
	"os"
	"strings"
)

func help() {
	fmt.Println("HttpAmi - a self-declared server - Version 1.0.0")
	flag.PrintDefaults()
}

type CmdInfo struct {
	Mode    string
	Port    int
	Channel string
	Cidr    string
	Ip      string
	N       int
	Me      string
}

func ParseArgs() (*CmdInfo, error) {
	flag.Usage = help
	arg := CmdInfo{}
	// 模式的识别
	var serverMode bool
	flag.BoolVar(&serverMode, "server", false, "server mode")
	var scanMode bool
	flag.BoolVar(&scanMode, "scan", false, "scan mode")
	// 参数定义 - 下方定义运行后才能自动生成程序的使用守则
	flag.StringVar(&arg.Me, "me", "", "your httpami server name")
	flag.StringVar(&arg.Channel, "channel", "AMI_DCH", "scan or setup httpami server with channel")
	flag.IntVar(&arg.Port, "port", 35250, "httpami server you setup or scan")
	flag.IntVar(&arg.N, "n", 10, "http goroutine count is 10, max is 30")
	flag.StringVar(&arg.Cidr, "cidr", "", "ip range you want to scan")
	flag.StringVar(&arg.Ip, "ip", "", "single ip you want to scan")
	// 解析并验证参数合法性
	flag.Parse()
	// // 打印识别的参数
	// fmt.Println(arg)
	// 获取Mode标记
	if len(os.Args) < 2 {
		help()
		return nil, errors.New("httami args is none")
	}
	arg.Mode = os.Args[1]
	// 验证合法性
	if serverMode {
		arg.Mode = "server"
		if arg.Me == "" {
			return nil, errors.New("server's me is none")
		} else if arg.Port < 10000 || arg.Port > 65535 {
			return nil, errors.New("port num is invaild")
		}
	} else if scanMode {
		arg.Mode = "scan"
		if arg.Cidr == "" && arg.Ip == "" {
			return nil, errors.New("cidr and ip all none")
		} else if arg.N <= 0 || arg.N > 30 {
			return nil, errors.New("goroutine count not between 1 and 30")
		}
	} else {
		return nil, errors.New("httami mode is scan or server, error mode")
	}
	// 将Channel转换为大写
	arg.Channel = strings.ToUpper(arg.Channel)
	return &arg, nil
}

func main() {
	arg, err := ParseArgs()
	if err != nil {
		fmt.Printf("err: %v\n", err)
		// help()
		return
	}
	// 启动相应的模式
	if arg.Mode == "server" {
		core.Init_ServerLogger()
		// 读取服务器配置
		conf := &core.JsonConfig{
			Me:      arg.Me,
			Port:    arg.Port,
			Channel: arg.Channel,
		}
		server := core.HttpAmiServer{}
		server.LoadConfig(conf) // 载入配置
		server.RunServer()      // 运行服务器
	} else if arg.Mode == "scan" {
		core.Init_ScanLogger()
		if arg.Ip != "" {
			fmt.Printf("scan-ip:%v\n", arg.Ip)
			sr := core.ScanOnce(arg.Ip, arg.Port, arg.Channel)
			if sr.Success {
				fmt.Printf("[True] me:%v , channel:%v\n", sr.Me, sr.Channel)
			} else {
				fmt.Printf("[False] err:%v\n", sr.Err)
			}
		} else if arg.Cidr != "" {
			fmt.Printf("scan-cidr:%v\n", arg.Cidr)
			isr, err := core.ScanCIDR(arg.Cidr, arg.Port, arg.Channel, arg.N)
			if err != nil {
				fmt.Printf("[False] err: %v\n", err)
				return
			}
			if len(isr) == 0 {
				fmt.Println("[False] None HTTPAMI Node FOUND")
			} else {
				fmt.Println("ALL SCAN LIST HEER:")
				for i, isr2 := range isr {
					fmt.Printf("[%v] -> me:%v , ip:%v\n", i, isr2.Me, isr2.Ip)
				}
			}
		}
	}
}
